import traceback
from collections import defaultdict
from itertools import chain

import pymongo
import time
import json
import requests
import redis
from wxpy import Bot, Group, TEXT, Tuling
from datetime import date, timedelta

# 127
client_127 = pymongo.MongoClient('mongodb://cs_user:cmcc5188@localhost:12018/cs_recharge')
db_127 = client_127.cs_recharge
coll_127 = db_127.rechange
conn = redis.Redis()
# 1688
client_1688 = pymongo.MongoClient(username='user', password='cmcc5188')
db_1688 = client_1688.recharge
coll_1688 = db_1688.rechange
bot = Bot(console_qr=2, cache_path="botoo.pkl")
groups = bot.groups()
group = None
for i in groups:
    if i.name == '127星恒太':
        group = i
if not group:
    print("找不到群")

prov_name = {'100': '北京',
             '200': '广东',
             '210': '上海',
             '220': '天津',
             '240': '辽宁',
             '250': '江苏',
             '270': '湖北',
             '280': '四川',
             '230': '重庆',
             '290': '陕西',
             '311': '河北',
             '351': '山西',
             '371': '河南',
             '431': '吉林',
             '451': '黑龙江',
             '471': '内蒙',
             '531': '山东',
             '551': '安徽',
             '571': '浙江',
             '591': '福建',
             '731': '湖南',
             '771': '广西',
             '791': '江西',
             '851': '贵州',
             '871': '云南',
             '891': '西藏',
             '898': '海南',
             '931': '甘肃',
             '951': '宁夏',
             '971': '青海',
             '991': '新疆'}


def get_ts():
    return str(time.time()).replace('.', '')[:13]


def get_unknow():
    res_85 = defaultdict(int)
    res_86 = defaultdict(int)
    today = date.today()
    yesterday = date.today() - timedelta(1)
    yesterday = yesterday.strftime('%Y%m%d')
    today = today.strftime('%Y%m%d')
    # 127

    cmcc_9 = conn.smembers('cmcc_9')

    # print("数量", conn.scard('unicom_9'), count_close)
    # count_close = 200
    # if conn.scard('cmcc_9') > count_close:
    #     is_close = conn.get("is_unicom_close")
    #     if is_close.decode() != '1':
    #         conn.set("is_close", 1)
    #         group.send("联通未知总数量大于%s关闭交易" % count_close)

    amount = 0
    for order in cmcc_9:
        order = order.decode()
        obj = coll_127.find_one({"ordernumber": order, "orderdate": today})
        if not obj:
            conn.srem('cmcc_9', order)
            continue
        if obj['orderstate'] != '9':
            conn.srem('cmcc_9', order)
        else:
            amount += int(obj['amount'])
            prov = obj.get('prov', "==")
            if obj.get('pay_type') == 'wx_h5':
                res_85[prov] += 1
                close_num = 5
                if res_85[prov] > close_num:
                    if not conn.sismember('unused_85_prov', prov):
                        # group.send("移动85%s未知总数量大于%s关闭交易" % (prov, close_num))
                        conn.sadd("unused_85_prov", prov)
            else:
                res_86[prov] += 1
                # close_num = 5
                # if res_86[prov] > close_num:
                #     if not conn.sismember('unused_86_prov', prov):
                #         group.send("移动86%s未知总数量大于%s关闭交易" % (prov, close_num))
                #         conn.sadd("unused_86_prov", prov)

    provs_85 = conn.smembers('unused_85_prov')
    for p in provs_85:
        if p.decode() not in res_85:
            conn.srem("unused_85_prov", p)

    provs_86 = conn.smembers('unused_86_prov')
    #for p in provs_86:
    #    if p.decode() not in res_86:
    #        conn.srem("unused_86_prov", p)
    res_86['未知总数'] = sum(res_86.values())
    count_close = 300
    if res_86['未知总数'] > count_close:
        is_close = conn.get("is_cmcc86_close")
        if is_close == b'0':
            conn.set("is_cmcc86_close", 1)
            group.send("86未知总数量大于%s关闭交易" % count_close)
    res_85['未知总数'] = sum(res_85.values())
    if res_85['未知总数'] > count_close:
        is_close = conn.get("is_cmcc86_close")
        if is_close == b'0':
            conn.set("is_cmcc85_close",  1)
            group.send("85未知总数量大于%s关闭交易" % count_close)
    return res_85, res_86

while True:
    start = time.time()
    try:
        res_85, res_86 = get_unknow()
        print('85', res_85)
        print('86', res_86)
        conn.delete("cmcc10085_unknow")
        conn.delete("cmcc10086_unknow")
        conn.hmset("cmcc10085_unknow", res_85)
        conn.hmset("cmcc10086_unknow", res_86)
    except Exception as e:
        traceback.print_exc()
    print("耗时", time.time() - start)
    # message = "; ".join(["%s:%s" % (k, v) for k, v in res.items()])
    # message = "各省未知数量：" + message
    # group.send(message)
    time.sleep(5 * 1)
